#include "task.hpp"
extern int errno;
void (*ps[3])();
void ReadTask(int fd)
{
    int cmd;
    while(true)
    {
        int n = read(fd,&cmd,sizeof(cmd));
        if(n == sizeof(cmd))
        {
            ps[cmd]();
        }
        else if(n == 0)
        {
            break;
        }
    }
}
void InitProcess(std::vector<Pipe> *v)
{
    for (int i = 0; i < N; i++)
    {
        int pipearr[2];
        int n = pipe(pipearr);
        if (n == -1)
        {
            // 失败；
            strerror(errno);
            return;
        }
        pid_t pid = fork();
        if (pid == 0)
        {
            close(pipearr[1]);
            //执行任务；
            ReadTask(pipearr[0]);
            exit(0);
        }
        else if (pid < 0)
        {
            strerror(errno);
            return;
        }
        close(pipearr[0]);
        v->push_back({pipearr[1], pid});
    }
}
void emun()
{
    std::cout << "####################################" << std::endl;
    std::cout << "#########1.创建一个线程#2.创建一个进程###############" << std::endl;
    std::cout << "##########3.求和   0.quit##########################" << std::endl;
}
void arrangTask(const std::vector<Pipe>&v)
{
    int cmd;
    int i = 0;
    while (true)
    {
        emun();
        std::cin >> cmd;
        if(cmd<0&&cmd>3)
        {
            continue;
        }
        else if(cmd == 0)
        {
            break;
        }
        write(v[i++].getCmdpipe(),&cmd,sizeof(cmd));
        i%=N;
        usleep(1000);
    }
}
void Quit(const std::vector<Pipe>&v)
{
    for(auto e:v)
    {
        close(e.getCmdpipe());
    }
    for(auto e:v)
    {
        int status;
        pid_t pid = waitpid(e.getChid(),&status,0);
        // std::cout<<"process pid:"<<e.getChid()<<"退出码："<<((status>>8)&0xff)<<" 错误码："<<status&0x7f<<std::endl;
        // std::cout<<"process pid:"<<e.getChid()<<"退出码："<<(status>>8)&0xff
        // std::cout<<std::endl;
    }
}
int main()
{
    setTask(ps);
    srand(time(nullptr));
    std::vector<Pipe> v;
    InitProcess(&v);
    arrangTask(v);
    Quit(v);
}